package cn.itcast.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Saka
 * Date: 2019/1/11
 * Time: 15:17
 */

@Component
public class KaFilter extends ZuulFilter{


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }


    //过滤业务
    @Override
    public Object run() throws ZuulException {
        //获取资源管理器
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = currentContext.getRequest();
        //从请求获取ka
        String ka = request.getParameter("ka");
        //判断
        if (StringUtils.isEmpty(ka)) {
            //如果为空,,拦截
            currentContext.setSendZuulResponse(false);//不响应内容
            currentContext.setResponseStatusCode(401);//未授权

        }

        //通过验证,可以考虑把用户信息放入资源管理器中,继续向后执行
        return null;
    }
}
